﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;
using System.IO.Ports;
using Microsoft.Office.Core;
using Excel = Microsoft.Office.Interop.Excel;
using MasterDatabase;

namespace Job_Assignment
{
    public partial class Form1 : SQL_APPL
    {
        readonly Color COLOR_SHIFTNAME_ON_LINE_INVALID = Color.Red;
        readonly Color COLOR_TOTAL_SHIFT_INVALID = Color.Red;
        readonly Color COLOR_TOTAL_SHIFT_VALID = Color.White;
        readonly Color COLOR_LINE_ODD = Color.White;
        readonly Color COLOR_LINE_EVEN = Color.WhiteSmoke;
        readonly Color COLOR_EDITABLE_COLUMN = Color.Violet;
        readonly Color COLOR_EDITABLE_COLUMN_LESS_ONE_SHIFT = Color.Green;
        
        MaterDatabase KeHoachSanXuatTheoNgayList_MasterDatabase;
        Button_Lbl PlanByDate_Create_BT;
        Button_Lbl PlanByDate_Calculate_BT;
        TextBox_Lbl txtTotalRequireResource;
        TextBox_Lbl txtInterestRequireResource;
        DataTable dtThreeShiftGroup = null;
        DataTable dtOneShiftGroup = null;
       // Button_Lbl PlanByDate_Check_BT;
        //Dho-Fixme: Do we need to use the button "Check_BT"?
        PlanByDateController planByDateController;
        List<string> EditableColumn = new List<string>() { "Date", "PartNumber", "Qty", "Priority" };

        public string KeHoachSanXuatTheoNgayList_Select_CMD = @"SELECT * FROM [JOB_ASSIGNMENT_DB].[dbo].[P_002_PlanForProductionByDate]";
        public string KeHoachSanXuatTheoNgayList_Init_Database_CMD = @"SELECT * FROM [JOB_ASSIGNMENT_DB].[dbo].[P_002_PlanForProductionByDate] 
                                                      WHERE [Date] = ''";
        private bool KeHoachSanXuatTheoNgayList_Exist = false;

        private bool KeHoachSanXuatTheoNgayList_Init()
        {
            if (KeHoachSanXuatTheoNgayList_Exist == true)
            {
                if (tabControl1.TabPages.Contains(KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_Tab) == false)
                {
                    tabControl1.TabPages.Insert(tabControl1.TabPages.Count, KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_Tab);
                }
                tabControl1.SelectTab("KeHoachSanXuatTheoNgay");
                return true;
            }
            KeHoachSanXuatTheoNgayList_Exist = true;
            Init_KeHoachSanXuatTheoNgay_Excel();
            //KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.AutoGenerateColumns = false;
            KeHoachSanXuatTheoNgayList_MasterDatabase = new MaterDatabase(OpenXL, tabControl1, "KeHoachSanXuatTheoNgay", ProductionPlanByDate_Index, MasterDatabase_Connection_Str, 
                                                            KeHoachSanXuatTheoNgayList_Init_Database_CMD, KeHoachSanXuatTheoNgayList_Select_CMD,
                                                            3, KeHoachSanXuatTheoNgay_Excel_Struct, filterStatusLabel, showAllLabel,
                                                            StatusLabel1, StatusLabel2, ProgressBar1);
            
            // Empl_Skill_List_MasterDatabase.MasterDatabase_GridviewTBL.dataGridView_View.Columns["Line_ID"].Frozen = true;
            KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.BackgroundColor = Color.White;

            planByDateController = new PlanByDateController(KeHoachSanXuatTheoNgayList_MasterDatabase);

            //Dho-Fixme: Do we need to use the button "Check_BT"?
            PosSize possize = new PosSize();
            possize.pos_x = 200;
            possize.pos_y = 90;
            PlanByDate_Create_BT = new Button_Lbl(1, KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_Tab, "Create", possize, (AnchorStyles)AnchorStyles.Left | AnchorStyles.Top);
            PlanByDate_Create_BT.My_Button.Click += new EventHandler(PlanByDate_Create_BT_Click);

            possize.pos_x = 300;
            possize.pos_y = 90;
            PlanByDate_Calculate_BT = new Button_Lbl(1, KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_Tab, "Calculate", possize, (AnchorStyles)AnchorStyles.Left | AnchorStyles.Top);
            PlanByDate_Calculate_BT.My_Button.Click += new EventHandler(Button_Calculte_Click);

            possize.pos_x = 700;
            possize.pos_y = 90;
            txtTotalRequireResource = new TextBox_Lbl(1, KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_Tab, "Total", TextBox_Type.TEXT, possize, AnchorType.LEFT);
            txtTotalRequireResource.My_TextBox.ReadOnly = true;
            txtTotalRequireResource.My_TextBox.TextAlign = HorizontalAlignment.Right;
            txtTotalRequireResource.My_TextBox.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));

            possize.pos_x = 880;
            txtInterestRequireResource = new TextBox_Lbl(1, KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_Tab, "Interest increasing", TextBox_Type.TEXT, possize, AnchorType.LEFT);
            txtInterestRequireResource.My_TextBox.Location = new Point(possize.pos_x + 100, possize.pos_y);
            txtInterestRequireResource.My_TextBox.ReadOnly = true;
            txtInterestRequireResource.My_TextBox.TextAlign = HorizontalAlignment.Right;
            txtInterestRequireResource.My_TextBox.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));

            DataTable dtShiftGroup = planByDateController.GetShiftGroup();
            dtThreeShiftGroup = dtShiftGroup.Clone();
            dtOneShiftGroup = dtShiftGroup.Clone();
            Utils.ImportRowToDataTable(ref dtThreeShiftGroup, dtShiftGroup.Select("Type=" + PlanByDateController.SHIFT_GROUP_TYPE_THREE.ToString()));
            Utils.ImportRowToDataTable(ref dtOneShiftGroup, dtShiftGroup.Select("Type=" + PlanByDateController.SHIFT_GROUP_TYPE_ONE.ToString()));
            dtThreeShiftGroup.Columns.Remove("Type");
            dtOneShiftGroup.Columns.Remove("Type");
            //dtOneShiftGroup = planByDateController.GetOneShiftGroup();
            
            //add column ShiftNamePerLine -> allow manual shiftname on line
            DataGridViewMultiColumnComboBoxColumn col = new DataGridViewMultiColumnComboBoxColumn();
            col.Name = "ShiftNamePerLine";
            col.DataPropertyName = "ShiftNamePerLine";
            col.DataSource = dtThreeShiftGroup;
            col.ValueMember = "GroupName";
            col.ColumnNames = new List<string> { "GroupName" };
            col.ColumnWidths = new List<string>() { "200" };

            if (KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.Columns.Contains("ShiftNamePerLine"))
            {
                int index = KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.Columns["ShiftNamePerLine"].Index;
                KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.Columns.RemoveAt(index);
                KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.Columns.Insert(index, col);
            }
            //end add column ShiftNamePerLine

            KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
            KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.ColumnHeadersHeight = 50;


            KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.Columns["TotalShiftPerLine"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.Columns["Capacity"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.Columns["Qty"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.Columns["NumOfShift"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.Columns["NumOfPerson_Per_Day"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.Columns["Shift_1_Qty"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.Columns["Shift_2_Qty"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.Columns["Shift_3_Qty"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.Columns["NumOfPerson_Per_Day"].Width = 70;
            KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.Columns["TotalShiftPerLine"].Width = 70;
            KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.Columns["Capacity"].Width = 70;
            KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.Columns["NumOfShift"].Width = 70;

            KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.Columns["Priority"].Width = 50;
            KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.Columns["Shift_1_From"].Width = 70;
            KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.Columns["Shift_1_To"].Width = 70;
            KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.Columns["Shift_1_Qty"].Width = 70;
            KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.Columns["Shift_1_Main"].Width = 70;
            KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.Columns["Shift_2_From"].Width = 70;
            KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.Columns["Shift_2_To"].Width = 70;
            KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.Columns["Shift_2_Main"].Width = 70;
            KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.Columns["Shift_2_Qty"].Width = 70;
            KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.Columns["Shift_3_From"].Width = 70;
            KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.Columns["Shift_3_To"].Width = 70;
            KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.Columns["Shift_3_Qty"].Width = 70;
            KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.Columns["Shift_3_Main"].Width = 70;

            KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.Columns["ShiftNamePerLine"].HeaderText = "Shift name per line";
            KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.Columns["TotalShiftPerLine"].HeaderText = "Total shift per line";
            KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.Columns["NumOfShift"].HeaderText = "Num of shift";
            KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.Columns["NumOfPerson_Per_Day"].HeaderText = "Num Of Person Per Day";
            KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.Columns["Shift_1_From"].HeaderText = "Shift_1 From";
            KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.Columns["Shift_1_To"].HeaderText = "Shift_1 To";
            KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.Columns["Shift_1_Qty"].HeaderText = "Shift_1 Qty";
            KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.Columns["Shift_1_Main"].HeaderText = "Shift_1 Main";
            KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.Columns["Shift_2_From"].HeaderText = "Shift_2 From";
            KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.Columns["Shift_2_To"].HeaderText = "Shift_2 To";
            KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.Columns["Shift_2_Qty"].HeaderText = "Shift_2 Qty";
            KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.Columns["Shift_2_Main"].HeaderText = "Shift_2 Main";
            KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.Columns["Shift_3_From"].HeaderText = "Shift_3 From";
            KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.Columns["Shift_3_To"].HeaderText = "Shift_3 To";
            KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.Columns["Shift_3_Qty"].HeaderText = "Shift_3 Qty";
            KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.Columns["Shift_3_Main"].HeaderText = "Shift_3 Main";
            KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.EditMode = DataGridViewEditMode.EditOnEnter;

            KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.CellValueChanged += new DataGridViewCellEventHandler(GridView_CellValueChanged);
            KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.CellContentClick += new DataGridViewCellEventHandler(GridView_CellContentClick);
            KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.Delete_Rows_BT.Visible = true;
            return true;
        }

        void GridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.CurrentCell.RowIndex == -1)
                return;
            int columnIndex = KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.CurrentCell.ColumnIndex;
            int rowIndex = KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.CurrentCell.RowIndex;

            string columnName = KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.Columns[columnIndex].Name;
            if (new List<string> { "Shift_1_Main", "Shift_2_Main", "Shift_3_Main" }.Contains(columnName))
            {
                KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.CommitEdit(DataGridViewDataErrorContexts.Commit);
            }
        }

        void GridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex  == -1)
                return;
            
            string columnName = KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.Columns[e.ColumnIndex].Name;

            DataTable inputTable = ((BindingSource)KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.DataSource).DataSource as DataTable;
            String subLineID = Utils.ObjectToString( KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView["SubLine_ID", e.RowIndex].Value);
            String partNumber = Utils.ObjectToString( KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView["PartNumber", e.RowIndex].Value);
            if (columnName == "ShiftNamePerLine")
            {
                //MessageBox.Show("Change " + KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.Columns[e.ColumnIndex].Name);
                String shiftNamePerLine = (String)KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView[e.ColumnIndex, e.RowIndex].Value;

                foreach (DataRow row in inputTable.Rows )
                {
                    String subLine = Utils.ObjectToString(row["SubLine_ID"]);

                    if (subLine == subLineID)
                    {
                        row["ShiftNamePerLine"] = shiftNamePerLine;
                    }
                }
                DateTime dateCalculate = Utils.ObjectToDecimal(KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView["Date", e.RowIndex].Value, DateTime.MinValue);

                if (dateCalculate != DateTime.MinValue)
                {
                    String ret = planByDateController.FillShiftNameFromAndToTime(dateCalculate, subLineID, ref inputTable);
                    if (!String.IsNullOrEmpty(ret))
                    {
                        Logger.GetInstance().WriteLogData("[P_002_PlanByDate]GridView_CellValueChanged: " + ret);
                        MessageBox.Show(ret);
                    }
                }
            }
            else if (new List<string> { "Shift_1_Main", "Shift_2_Main", "Shift_3_Main" }.Contains(columnName))
            {
                String shitColumnName = columnName.Replace("_Main", "");
                //bool oldValue = false;
                bool oldValue = !Utils.ObjectToBoolean(KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView[e.ColumnIndex, e.RowIndex].Value, false);

                //if (KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView[e.ColumnIndex, e.RowIndex].Value != DBNull.Value)
                //{
                //    oldValue = !(Boolean)KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView[e.ColumnIndex, e.RowIndex].Value;
                //}
                if (!oldValue && Utils.ObjectToDecimal(KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView[shitColumnName + "_Qty", e.RowIndex].Value, 0) > 0)
                {
                    string ret = planByDateController.ChangeMainPart(ref inputTable, subLineID, partNumber, shitColumnName, oldValue);

                    if (!String.IsNullOrEmpty(ret))
                        MessageBox.Show(ret);
                }
            }
        }

        void FormatDataGridViewDisplay()
        {
            DataTable inputTable = ((BindingSource)KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.DataSource).DataSource as DataTable;
            //check rule
            Dictionary<String, bool> lineRule = new Dictionary<string, bool>();
            String ret = planByDateController.GetLineRule(inputTable, ref lineRule);
            if (!String.IsNullOrEmpty(ret))
            {
                MessageBox.Show(ret);
                return;
            }
            //set readonly
            foreach (DataGridViewColumn column in KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.Columns)
            {
                if (!EditableColumn.Contains(column.Name))
                {
                    column.ReadOnly = true;
                }
            }

            DataGridViewRow lastRow = null; 
            foreach (DataGridViewRow row in KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.Rows)
            {
                if (row.IsNewRow)
                    continue;

                String shiftNamePerLine = Utils.ObjectToString(row.Cells["ShiftNamePerLine"].Value);
                String subLineID = Utils.ObjectToString(row.Cells["SubLine_ID"].Value);
                if (lastRow == null)
                {
                    row.DefaultCellStyle.BackColor = COLOR_LINE_ODD;
                }
                else
                {
                    if (subLineID == Utils.ObjectToString(lastRow.Cells["SubLine_ID"].Value))
                    {
                        row.DefaultCellStyle.BackColor = lastRow.DefaultCellStyle.BackColor;
                    }
                    else
                    {
                        row.DefaultCellStyle.BackColor = lastRow.DefaultCellStyle.BackColor == COLOR_LINE_EVEN ? COLOR_LINE_ODD : COLOR_LINE_EVEN;
                    }
                }
                foreach (string col in EditableColumn)
                {
                    row.Cells[col].Style.BackColor = COLOR_EDITABLE_COLUMN;
                }
                lastRow = row;
                //high line totalshift > 3
                object sDate = row.Cells["Date"].Value;
                if (sDate != null && !String.IsNullOrEmpty(sDate.ToString()))
                {
                    DateTime dt;
                    bool b = DateTime.TryParse(sDate.ToString(), out dt);
                    if (b)
                    {
                        String partNumber = row.Cells["PartNumber"].Value as String;
                        String key = String.Format("{0}_{1}", dt.ToString("dd/MM/yyyy"), partNumber);
                        row.Cells["TotalShiftPerLine"].Style.BackColor = lineRule[key] ? COLOR_TOTAL_SHIFT_INVALID : row.Cells["TotalShiftPerLine"].Style.BackColor;
                    }
                }
                //highlight invalid line -> cannot arrange shift
                if ( String.IsNullOrEmpty(Utils.ObjectToString(row.Cells["ShiftNamePerLine"].Value)))
                {
                    row.Cells["TotalShiftPerLine"].Style.BackColor = COLOR_SHIFTNAME_ON_LINE_INVALID;
                    row.Cells["ShiftNamePerLine"].Style.BackColor = COLOR_SHIFTNAME_ON_LINE_INVALID;
                }

                if (shiftNamePerLine == PlanByDateController.SHIFT_1_SHIFT_3 || shiftNamePerLine == PlanByDateController.SHIFT_1_SHIFT_2_SHIFT_3)
                {
                    row.Cells["ShiftNamePerLine"].ReadOnly = false;
                    row.Cells["ShiftNamePerLine"].Style.BackColor = COLOR_EDITABLE_COLUMN; 

                    var cell = row.Cells["ShiftNamePerLine"] as DataGridViewMultiColumnComboBoxCell;
                    cell.DataSource = dtThreeShiftGroup;
                    cell.ColumnNames = new List<string> { "GroupName" };
                }

                decimal totalShiftPerLine = Utils.ObjectToDecimal(row.Cells["TotalShiftPerLine"].Value, -1);
                if (totalShiftPerLine > 0 && totalShiftPerLine < 1)
                {
                    row.Cells["ShiftNamePerLine"].ReadOnly = false;
                    row.Cells["ShiftNamePerLine"].Style.BackColor = COLOR_EDITABLE_COLUMN_LESS_ONE_SHIFT; 
                    var cell = row.Cells["ShiftNamePerLine"] as DataGridViewMultiColumnComboBoxCell;
                    cell.DataSource = dtOneShiftGroup;
                    cell.ColumnNames = new List<string> { "GroupName" };
                }

                foreach (string shift in new List<string> { "Shift_1", "Shift_2", "Shift_3" })
                {
                    if (Utils.ObjectToDecimal(row.Cells[shift+ "_Qty"].Value, -1) > 0)
                    {
                        row.Cells[shift + "_Main"].ReadOnly = false;
                        row.Cells[shift + "_Main"].Style.BackColor = COLOR_EDITABLE_COLUMN;
                    }
                }
            }

        }

        void Button_Calculte_Click(object sender, EventArgs e)
        {
            bool b = KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.Update_SQL_Data(KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.Data_da, KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.Data_dtb);
            if (b)
            {
                FormatDataGridViewDisplay();
                DateSelect_Dialog_Form selectDate_Dialog = new DateSelect_Dialog_Form(DateTime.Now);
                if (selectDate_Dialog.ShowDialog() == DialogResult.OK)
                {
                    DateTime dt = selectDate_Dialog.Select_Date;
                    //load data by date
                    b = KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.Load_DataBase(MasterDatabase_Connection_Str, String.Format("SELECT * FROM [JOB_ASSIGNMENT_DB].[dbo].[P_002_PlanForProductionByDate] WHERE [Date] = '{0}' order by SubLine_ID", dt.ToString("yyyy-MMM-dd")));

                    if (b)
                    {
                        String ret = Calculate(dt);
                        if (!String.IsNullOrEmpty(ret))
                        {
                            MessageBox.Show(ret);
                        }
                    }
                }
                else
                {
                }
            }
        }

        private string Calculate(DateTime dateCalculate)
        {
            DataTable tbResult = new DataTable();
            DataTable inputPlan = ((BindingSource)KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.DataSource).DataSource as DataTable;
            String ret = planByDateController.Calculate(dateCalculate, ref inputPlan, ref tbResult);
            if (!String.IsNullOrEmpty(ret))
            {
                return ret;
            }
            foreach (DataRow r in inputPlan.Rows)
            {
                r.Delete();
            }
            foreach (DataRow r in tbResult.Rows)
            {
                inputPlan.ImportRow(r);
            }
            bool b = KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.Update_SQL_Data(KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.Data_da, KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.Data_dtb);
            if (!b)
            {
                ret = "Cannot update datable";
                return ret;
            }

            //re-binding 
            //BindingSource bs = new BindingSource();
            //bs.DataSource = tbResult;
            //KeHoachSanXuatTheoNgayList_MasterDatabase.MasterDatabase_GridviewTBL.GridView.DataSource = bs;

            //show TotalResource
            int totalResource = 0;
            ret = planByDateController.GetTotalResource(inputPlan, ref totalResource);
            if (!String.IsNullOrEmpty(ret))
            {
                return ret;
            }
            txtTotalRequireResource.My_TextBox.Text = totalResource.ToString("###,###,###,###");

            //show interest resouce

            double interest = 0;
            ret = planByDateController.GetInterestRequireResource(totalResource, ref interest);
            if (!String.IsNullOrEmpty(ret))
            {
                return ret;
            }
            txtInterestRequireResource.My_TextBox.Text = String.Format("{0}%", interest);

            FormatDataGridViewDisplay();
            return "";
        }

        ExcelImportStruct[] KeHoachSanXuatTheoNgay_Excel_Struct;
        const int KeHoachSanXuatTheoNgay_INDEX = 0;

        private void Init_KeHoachSanXuatTheoNgay_Excel()
        {
            if (KeHoachSanXuatTheoNgay_Excel_Struct == null)
            {
                KeHoachSanXuatTheoNgay_Excel_Struct = new ExcelImportStruct[4];
                
                KeHoachSanXuatTheoNgay_Excel_Struct[0] = new ExcelImportStruct(0, "Date", "Date", Excel_Col_Type.COL_DATE, 10, true);
                KeHoachSanXuatTheoNgay_Excel_Struct[1] = new ExcelImportStruct(1, "PartNumber", "PartNumber", Excel_Col_Type.COL_STRING, 20, true);
                KeHoachSanXuatTheoNgay_Excel_Struct[2] = new ExcelImportStruct(2, "Priority", "Priority", Excel_Col_Type.COL_INT, 20, false);
                //KeHoachSanXuatTheoNgay_Excel_Struct[2] = new ExcelImportStruct(2, "LineID", "LineID", Excel_Col_Type.COL_STRING, 20, false);
                //KeHoachSanXuatTheoNgay_Excel_Struct[3] = new ExcelImportStruct(3, "LineName", "LineName", Excel_Col_Type.COL_STRING, 50, false);
                //KeHoachSanXuatTheoNgay_Excel_Struct[4] = new ExcelImportStruct(4, "GroupID", "GroupID", Excel_Col_Type.COL_STRING, 20, false);
                //KeHoachSanXuatTheoNgay_Excel_Struct[5] = new ExcelImportStruct(5, "TotalShiftPerLine", "TotalShiftPerLine", Excel_Col_Type.COL_STRING, 50, false);
                //KeHoachSanXuatTheoNgay_Excel_Struct[6] = new ExcelImportStruct(6, "Capacity", "Capacity", Excel_Col_Type.COL_INT, 20, false);
                KeHoachSanXuatTheoNgay_Excel_Struct[3] = new ExcelImportStruct(3, "Qty", "Qty", Excel_Col_Type.COL_INT, 20, false);
                //KeHoachSanXuatTheoNgay_Excel_Struct[8] = new ExcelImportStruct(8, "NumOfShift", "NumOfShift", Excel_Col_Type.COL_FLOAT, 20, false);
                //KeHoachSanXuatTheoNgay_Excel_Struct[9] = new ExcelImportStruct(9, "NumOfPerson_Per_Day", "NumOfPerson_Per_Day", Excel_Col_Type.COL_INT, 50, false);
            }
        }
    }
}